package com.industry.system.service;

import cn.hutool.core.exceptions.ValidateException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.industry.framework.common.page.PageConverter;
import com.industry.framework.common.page.PageQuery;
import com.industry.framework.common.page.TableDataInfo;
import com.industry.framework.common.utils.RSAUtils;
import com.industry.system.controller.vo.SystemUserRespVO;
import com.industry.system.convert.SystemUserConvert;
import com.industry.system.dal.dataobject.SystemUser;
import com.industry.system.dal.dataobject.SystemUserRole;
import com.industry.system.dal.db.SystemUserMapper;
import com.industry.system.dal.db.SystemUserRoleMapper;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class UserService {

    @Resource
    private SystemUserMapper systemUserMapper;

    @Resource
    private SystemUserRoleMapper systemUserRoleMapper;


    public TableDataInfo<SystemUser> getAllSystemCodes(PageQuery pageQuery){
        Page<SystemUser> systemCodePage = systemUserMapper.selectPage(pageQuery.build(), new QueryWrapper<>());
        return TableDataInfo.build(PageConverter.convert(systemCodePage, SystemUser.class));
    }

    public SystemUserRespVO  querySystemUserById(String userId){
        if(null != userId){
            //获取当前用户信息
            SystemUser systemUser = systemUserMapper.selectById(Long.valueOf(userId));
            //获取用户角色
            LambdaQueryWrapper<SystemUserRole> queryWrapper = Wrappers.lambdaQuery(SystemUserRole.class)
                    .eq(SystemUserRole::getUserId,userId);
            List<SystemUserRole> list = systemUserRoleMapper.selectList(queryWrapper);
            List<String> roleIds = list.stream().map(SystemUserRole::getRoleId).collect(Collectors.toList());
            if(systemUser != null){
                SystemUserRespVO convert = SystemUserConvert.INSTANCE.convert(systemUser);
                if(!CollectionUtils.isEmpty(roleIds)){
                    convert.setRoleIds(StringUtils.join(roleIds,","));
                }
                return convert;
            }
        }
        return new SystemUserRespVO();
    }

    public List<SystemUser> queryAllSystemCode(){
        return systemUserMapper.selectList(new QueryWrapper<>());
    }


    @Transactional(rollbackFor = Exception.class)
    public int insert(SystemUser systemUser){
        systemUser.setTenantId("1");
        systemUser.setPassword(RSAUtils.encrypt("123456"));
        return systemUserMapper.insert(systemUser);
    }

    /**
     * 修改用户信息
     * @param systemUserRespVO
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int modify(SystemUserRespVO systemUserRespVO){
        String roleIds = systemUserRespVO.getRoleIds();
        if(StringUtils.isEmpty(roleIds)){
            throw new ValidateException("【保存用户信息数据异常】缺少角色数据。");
        }
        //修改用户与角色
        updateUserRoleMapInfo(systemUserRespVO.getId(),Arrays.asList(roleIds.split(",")));
        return systemUserMapper.updateById(systemUserRespVO);
    }

    private void updateUserRoleMapInfo(String userId , List<String> roleIdsList){
        //查询当前 用户 与 角色已绑定的映射数据
        LambdaQueryWrapper<SystemUserRole> queryWrapper = Wrappers.lambdaQuery(SystemUserRole.class)
                .eq(SystemUserRole::getUserId,userId);
        List<SystemUserRole> systemUserRoles = Collections.unmodifiableList(systemUserRoleMapper.selectList(queryWrapper));
        List<SystemUserRole> collectDel = null;
        List<SystemUserRole> collectAdd = new ArrayList<>();
        if(!CollectionUtils.isEmpty(systemUserRoles)){
            //待删除数据
            collectDel = systemUserRoles.stream().filter(i -> {
                return !roleIdsList.contains(i.getRoleId());
            }).toList();
            for (String roleId : roleIdsList) {
                boolean a = systemUserRoles.stream().map(SystemUserRole::getRoleId).toList().contains(roleId);
                if(!a){
                    SystemUserRole s = this.buildAddInfo(userId,roleId);
                    collectAdd.add(s);
                }
            }
        }else{
            for (String roleId : roleIdsList) {
                SystemUserRole s = this.buildAddInfo(userId,roleId);
                collectAdd.add(s);
            }
        }
        if(!CollectionUtils.isEmpty(collectDel)){
            systemUserRoleMapper.deleteByIds(collectDel.stream().map(SystemUserRole::getId).collect(Collectors.toList()));
        }
        if(!CollectionUtils.isEmpty(collectAdd)){
            systemUserRoleMapper.insert(collectAdd);
        }
    }

    private SystemUserRole buildAddInfo(String userId , String roleId){
        SystemUserRole s = new SystemUserRole();
        s.setRoleId(roleId);
        s.setUserId(userId);
        return s;
    }

}
